package net.huashitong.oversee.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.oversee.dao.GradePointDao;
import net.huashitong.oversee.entity.*;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.utils.UtilsTools;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

//绩效考核分数评定
@Service
public class GradePointService extends StringPKService<GradePoint> {

    @Autowired
    private GradePointDao dao;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private SupervisionLogService tasklogservice;
    @Autowired
    private TaskMethonService methonService;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;

    @Override
    protected BaseDao<GradePoint, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(GradePoint obj) {
        obj.setSysId(tableService.updateMaxSysId("t_gradepoint", null));
    }

    public List<GradePoint> queryAll(GradePointFilter filter) {
        return dao.queryAllGradePoint(filter);
    }

    //条件搜索

    public List<GradePoint> queryGradePoint(GradePointFilter filter) {
        return dao.queryGradePoint(filter);
    }

    /**
     * 考评分， 督查项得分/督查次数
     * <p>
     * 针对督查组的考评，建议如下：1.采取积分制，在平均分基础上，根据督查项目数酌情加分。
     * 2.督查总分100分，第一轮督查后能顺利推进节点的，得100分。需多轮督查的（最多3轮），每轮最多得30分。
     * 3.每季度汇总得分排名情况，根据排名情况确定绩效奖励对象。
     * 4.多轮督查，督查过程得分计分标准：
     * 开展电话或现场督查5分、发出催办单或督办单5分、找出项目存在问题5分、进行约谈10分、提出处理意见5。
     *
     * @param task
     */
    public String saveGroupSocure(SupervisionTask task) {

        GradePoint grade = new GradePoint();
        Double soucre = 0.0;
        //判断该分数是否录入
        GradePoint tempgrade = new GradePoint();
        List<GradePoint> gradePoints = getGradeById(task.getSysId());
        if (gradePoints.size() > 0) {
            for (GradePoint g : gradePoints) {
                if ("督查单位".equals(g.getCheckType())) {
                    //g->tempgrade
                    tempgrade = g;
                }
            }
        }
//        //按时完成
//        Date endDate = null;
//        Date planeDate = null;
//        try {
//            endDate = UtilsTools.StringToDate(StringUtils.isNotBlank(task.getEndDate())?task.getEndDate():UtilsTools.getCurrentDate());
//            planeDate = UtilsTools.StringToDate(task.getPlanEndDate());
//        } catch (ParseException e) {
//            e.printStackTrace();
//            log.info("-----------计算督查组得分时间格式 endDate:"+endDate+"-----------");
//            log.info("-----------计算督查组得分时间格式 planeDate:"+planeDate+"-----------");
//        }

        // 一轮督查且顺利完成。
        if ("1".equals(task.getSupervisionResult()) && "1".equals(task.getTaskResult()) && "1".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("100.0");
        } else if("1".equals(task.getSupervisionResult()) && "1".equals(task.getTaskResult()) && "2".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("60.0");
        }else if("1".equals(task.getSupervisionResult()) && "1".equals(task.getTaskResult()) && "3".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("40.0");
        }else {
            //二轮督查 或者超时间 为未完成
            //判断是否有督查记录。
            List<SupervisionLog> lists = tasklogservice.getMissionLog(task.getSysId());
            if (ObjectUtils.isBlank(lists)) {
                grade.setTaskId(task.getSysId());
                grade.setSoucre("0.0");
            } else {
                for (SupervisionLog item : lists) {
                    TaskMethon methons = methonService.getMethon(item.getMethonCode());
                    if (ObjectUtils.isNotBlank(methons)) {
                        soucre = Integer.parseInt(methons.getScore()) + soucre;
                    }
                }
                grade.setTaskId(task.getSysId());
                if (soucre > 30.0) {
                    soucre = 30.0; //最高分 30分。
                }
                grade.setSoucre(String.format("%.1f", soucre) + "");
            }
        }
        grade.setTaskContent(task.getTaskContent());
        grade.setCheckObject(task.getGroupType());
        grade.setCheckObjectId(task.getGroupId());
        grade.setCheckType("督查单位");
        grade.setTaskName(task.getTaskName());
        if (StringUtils.isBlank(tempgrade.getSysId()))  //判断是否已经有记录分数记录。有则更新，无则新建
        {
            save(grade);
            log.info("保存绩效成绩 ");
        } else {
            tempgrade.setSoucre(grade.getSoucre());
            tempgrade.setTaskName(grade.getTaskName());
            update(tempgrade);
            log.info("更新绩效成绩 ");
        }
        task.setSupervisionScore(grade.getSoucre());
        supervisionTaskService.update(task);
        return grade.getSoucre();
    }


    /**
     * 业主单位评分。每完成1个节点得100分，
     * 节点逾期后在首轮督查任务时限完成得80分，
     * 次轮完成的得60分，第三轮完成的得40分，
     * 三轮督查后仍未完成扣50分。如：城投公司3个节点任务，
     * 1个按时完成，2个首轮督查后完成，绩效积分为：
     * （1x100+2x80）÷3+（1x100+2x80）÷10=112.6。
     */
    public String saveGroupScoreInOperator(SupervisionTask task) throws ParseException {

        String operatorUser = task.getOperatorUser();
        String operatorPhone = task.getOperatorPhone();
        BnpUser bnpUser = bnpUserService.getBnpUserByPhoneAndName(operatorPhone, operatorUser);

        GradePoint grade = new GradePoint();

        //判断该分数是否录入
        GradePoint tempgrade = new GradePoint();
        List<GradePoint> gradePoints = getGradeById(task.getSysId());

        if (ObjectUtils.isNotBlank(bnpUser)) {
            if (gradePoints.size() > 0) {
                for (GradePoint g : gradePoints) {
                    if ("0".equals(bnpUser.getBranchType())) {
                        if ("业主单位经办人".equals(g.getCheckType())) {
                            tempgrade = g;
                        }
                    }
                    if ("1".equals(bnpUser.getBranchType())) {
                        if ("审批部门经办人".equals(g.getCheckType())) {
                            tempgrade = g;
                        }
                    }
                }
            }
        }

        Date endDate = UtilsTools.StringToDate(task.getPlanEndDate());//计划结束时间，
        Date currentDate = UtilsTools.StringToDate(UtilsTools.getCurrentDate());//当前日期
        int flag = endDate.compareTo(currentDate); //计划结束时间和当前时间比较。是否到期。

        // 一轮督查且顺利完成。
        if ("1".equals(task.getTaskResult()) &&
                "1".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("80.0");
        } else if ("1".equals(task.getTaskResult()) &&
                "2".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("60.0");
        } else if ("1".equals(task.getTaskResult()) &&
                "3".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("40.0");
        } else if ("0".equals(task.getTaskResult()) &&
                ("1".equals(task.getTasktimes())
                        || "2".equals(task.getTasktimes())
                )) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("0.0");
        } else if("0".equals(task.getTaskResult()) &&
                flag >= 0 && "3".equals(task.getTasktimes())){
            grade.setTaskId(task.getSysId());
            grade.setSoucre("0.0");
        } else{
            grade.setTaskId(task.getSysId());
            grade.setSoucre("-50.0");
        }
        grade.setTaskContent(task.getTaskContent());
        grade.setCheckObject(task.getOperatorUser());
        if (ObjectUtils.isNotBlank(bnpUser)) {
            if ("0".equals(bnpUser.getBranchType())) {
                grade.setCheckType("业主单位经办人");
                grade.setCheckObjectId(bnpUser.getSysId());
                grade.setResDept(bnpUser.getBranch());
            }
            if ("1".equals(bnpUser.getBranchType())) {
                grade.setCheckType("审批部门经办人");
                grade.setCheckObjectId(bnpUser.getSysId());
                grade.setResDept(bnpUser.getBranch());
            }
        } else {
//            return null;
            grade.setResDept("未知单位");
            return null;
        }
        grade.setTaskName(task.getTaskName());
        //判断是否已经有记录分数记录。有则更新，无则新建
        if (ObjectUtils.isBlank(tempgrade.getSysId())) {
            save(grade);
            log.info("保存绩效成绩 ");
        } else {
            tempgrade.setSoucre(grade.getSoucre());
            tempgrade.setTaskName(grade.getTaskName());
            update(tempgrade);
            log.info("更新绩效成绩");
        }
        //返回得分
        task.setRespScore(grade.getSoucre());
        supervisionTaskService.update(task);
        return grade.getSoucre();
    }

    /**
     * 审批单位。每完成1个节点得100分，
     * 节点逾期后在首轮督查任务时限完成得80分，
     * 次轮完成的得60分，第三轮完成的得40分，
     * 三轮督查后仍未完成扣50分。如：
     * 住建局有5个审批节点任务，
     * 全部按时完成，绩效积分为：5x100÷5+5x100÷10=150。
     */
    public String saveGroupSocureInApproval(SupervisionTask task) throws ParseException {
        return saveGroupScoreInOperator(task);
    }

    public String saveGroupScoreInResUer(SupervisionTask task) throws ParseException {
        //责任人
        String resUser = task.getResUser();
        String resPhone = task.getResPhone();
        BnpUser bnpUser = bnpUserService.getBnpUserByPhoneAndName(resPhone, resUser);

        GradePoint grade = new GradePoint();

        //判断该分数是否录入
        GradePoint tempgrade = new GradePoint();
        List<GradePoint> gradePoints = getGradeById(task.getSysId());

        Date endDate = UtilsTools.StringToDate(task.getPlanEndDate());//计划结束时间，
        Date currentDate = UtilsTools.StringToDate(UtilsTools.getCurrentDate());//当前日期
        int flag = endDate.compareTo(currentDate); //计划结束时间和当前时间比较。是否到期。

        if (ObjectUtils.isNotBlank(bnpUser)) {
            if (gradePoints.size() > 0) {
                for (GradePoint g : gradePoints) {
                    if ("0".equals(bnpUser.getBranchType())) {
                        if ("业主单位责任人".equals(g.getCheckType())) {
                            tempgrade = g;
                        }
                    }
                    if ("1".equals(bnpUser.getBranchType())) {
                        if ("审批部门责任人".equals(g.getCheckType())) {
                            tempgrade = g;
                        }
                    }
                }
            }
        }

        // 一轮督查且顺利完成。
        if ("1".equals(task.getTaskResult()) &&
                "1".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("80.0");
        } else if ("1".equals(task.getTaskResult()) &&
                "2".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("60.0");
        } else if ("1".equals(task.getTaskResult()) &&
                "3".equals(task.getTasktimes())) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("40.0");
        } else if ("0".equals(task.getTaskResult()) &&
                ("1".equals(task.getTasktimes())
                        || "2".equals(task.getTasktimes()))) {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("0.0");
        }  else if("0".equals(task.getTaskResult()) &&
                flag >= 0 && "3".equals(task.getTasktimes())){
            grade.setTaskId(task.getSysId());
            grade.setSoucre("0.0");
        }else {
            grade.setTaskId(task.getSysId());
            grade.setSoucre("-50.0");
        }
        grade.setTaskContent(task.getTaskContent());
        grade.setCheckObject(task.getResUser());
        if (ObjectUtils.isNotBlank(bnpUser)) {
            if ("0".equals(bnpUser.getBranchType())) {
                grade.setCheckType("业主单位责任人");
                grade.setCheckObjectId(bnpUser.getSysId());
                grade.setResDept(bnpUser.getBranch());
            }
            if ("1".equals(bnpUser.getBranchType())) {
                grade.setCheckType("审批部门责任人");
                grade.setCheckObjectId(bnpUser.getSysId());
                grade.setResDept(bnpUser.getBranch());
            }
        } else {
//            return null;
            grade.setResDept("未知单位");
            return null;
        }
        grade.setTaskName(task.getTaskName());
        //判断是否已经有记录分数记录。有则更新，无则新建
        if (ObjectUtils.isBlank(tempgrade.getSysId())) {
            save(grade);
            log.info("保存绩效成绩 ");
        } else {
            tempgrade.setSoucre(grade.getSoucre());
            tempgrade.setTaskName(grade.getTaskName());
            update(tempgrade);
            log.info("更新绩效成绩");
        }
        //返回得分
        task.setRespScore(grade.getSoucre());
        supervisionTaskService.update(task);
        return grade.getSoucre();
    }

    public List<GradePoint> getGradeById(String id) {
        return dao.getGradePointById(id);
    }

    public List<GradePoint> queryGradePointByIds(List<String> ids) {
        return dao.queryGradePointByIds(ids);
    }

    public List<GradePoint> queryGradePointByCheckType(String checkType) {
        return dao.queryGradePointByCheckType(checkType);
    }

    //删掉考核记录中的重复数据
    public void deleteRepeatData(){
        List<GradePoint> gradePoints = this.query();
        List<GradePoint> needDelete = new ArrayList<>();
        Map<String,Object> gradePointsMap = new HashMap<>();
        for(GradePoint g : gradePoints){
            if(!gradePointsMap.containsKey(g.getCheckObject()+g.getTaskId())){
                gradePointsMap.put(g.getCheckObject()+g.getTaskId(),g);
            }else{
                needDelete.add(g);
            }
        }
        this.batchDeleteObject(needDelete);
    }

    public void updateRank(){
        //绩效得分设置无效标志
        //查询所有绩效得分
        List<GradePoint> gradePoints = this.query();
        //查询所有失效的任务
        List<String> invalidTasks = new ArrayList<>();
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setValid("0");
        List<SupervisionTask> tasks = supervisionTaskService.getTaskListsNoPage(taskFilter);
        for (SupervisionTask t : tasks) {
            invalidTasks.add(t.getSysId());
        }
        for (GradePoint g : gradePoints) {
            if(invalidTasks.contains(g.getTaskId())){
                //1表示失效的绩效得分
                g.setInvalid("1");
            }
        }
        this.batchUpdate(gradePoints);

        //查询有效的绩效得分
        List<GradePoint> list = dao.queryAllValidGradePoint();

        Collections.sort(list, new Comparator<GradePoint>() {
            @Override
            public int compare(GradePoint g1, GradePoint g2) {
                double score1 = Double.parseDouble(StringUtils.isBlank(g1.getSoucre()) ? "0" : g1.getSoucre());
                double score2 = Double.parseDouble(StringUtils.isBlank(g2.getSoucre()) ? "0" : g2.getSoucre());
                if (score1 < score2) {
                    return 1;
                } else if (score1 == score2) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        for (int i = 0, s = list.size(); i < s; i++) {
            if (i > 0 && Double.parseDouble(StringUtils.isBlank(list.get(i).getSoucre()) ? "0" : list.get(i).getSoucre())
                    == Double.parseDouble(StringUtils.isBlank(list.get(i - 1).getSoucre()) ? "0" : list.get(i - 1).getSoucre())) {
                list.get(i).setRank(list.get(i - 1).getRank());
            } else {
                list.get(i).setRank(i + 1 + "");
            }
        }
        this.batchUpdate(list);
    }

    //查询（已完成、已考核的绩效评分）
    public List<GradePoint> queryChecked(){
        return  dao.queryChecked();
    }

    //查询（已完成、已考核的绩效评分）+ 时间范围 + 条件
    public List<GradePoint> queryCheckedInTime(ScoreSummaryFilter filter){
        return  dao.queryCheckedInTime(filter);
    }

    //根据督查任务taskId批量删除绩效成绩
    public void deletAllInvalidTaskGradePoint(List<String> taskIds){
        dao.deletAllInvalidTaskGradePoint(taskIds);
    }

    /**
     * 查询未进入督查的绩效得分
     * @return
     */
    public List<GradePoint> querySuccessfulGradePoint(){
        return dao.querySuccessfulGradePoint();
    }


    /**
     * 查询未进入督查的绩效得分(有时间段)
     * @return
     */
    public List<GradePoint> querySuccessfulGradePointInTime(ScoreSummaryFilter filter){
        return dao.querySuccessfulGradePointInTime(filter);
    }

    public List<Map<String, Object>> getScoreNumCount(GradePointFilter filter){
        return dao.getScoreNumCount(filter);
    }

    public List<GradePoint> queryByProjectId(String projectId){
        return dao.queryByProjectId(projectId);
    }

    public List<GradePoint> queryTackToTaskGradePointList(GradePointFilter filter){
        return dao.queryTackToTaskGradePointList(filter);
    }
}
